import { logMgr } from "../Manager/LogMgr"
import { timerMgr } from "../Manager/TimerMgr"

export class BaseTimer {

    private cache: Map<string, number> = new Map<string, number>()
    private _target: any = null

    constructor(target: any) {
        this._target = target
    }
    /**
     * 创建定时器
     * @param key 标识ID 
     * @param callback 回调
     * @param interval 定时间隔 单位秒
     * @param delay 是否需要延迟回调 默认立即回调一次
     * @returns 
     */
    create(key: string, callback: Function, interval: number, delay: boolean = false) {
        if (this.cache.get(key)) {
            logMgr.warn(`重复添加计时器[ ${key} ]`)
            return
        }
        if (!delay) {
            callback.call(this._target, 0)
        }
        let timerId = timerMgr.create(this._target, callback, interval)
        this.cache.set(key, timerId)
    }

    createOnce(key: string, callback: Function, interval: number, delay: boolean = false) {
        if (this.cache.get(key)) {
            logMgr.warn(`重复添加计时器[ ${key} ]`)
            return
        }
        if (!delay) {
            callback.call(this._target, 0)
        }

        let timerId
        timerId = timerMgr.create(this._target, () => {
            callback()
            this.stopTimer(key)
        }, interval)
        this.cache.set(key, timerId)
    }

    hasTimer(key: string) {
        if (this.cache.has(key)) {
            return true
        }
        return false
    }

    pauseTimer(key: string) {
        let timerId = this.cache.get(key)
        if (timerId) {
            timerMgr.pause(timerId)
        }
    }

    resumeTimer(key: string) {
        let timerId = this.cache.get(key)
        if (timerId) {
            timerMgr.resume(timerId)
        }
    }

    isTimerPaused(key: string): boolean {
        let timerId = this.cache.get(key)
        if (timerId) {
            return timerMgr.isPaused(timerId)
        }
        return false
    }

    stopTimer(key: string) {
        let timerId = this.cache.get(key)
        if (timerId) {
            timerMgr.stop(timerId)
            this.cache.delete(key)
        }
    }

    public stopAllTimer() {
        this.cache.forEach((timerId, key) => {
            timerMgr.stop(timerId)
        })
        this.cache.clear()
    }
}